<?php

namespace App\Console\Commands\OpenShop\Nsq;


use App\Enums\Common\NsqEnum;
use App\Library\FeiShu\SendFs;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Kuafu\GeneralFs\BuildFs;
use Kuafu\Nsq\NsqSubscriber;
use NSQClient\Contract\Message;

class NsqSubFirstUnifiedOrderCommand extends Command
{
    protected $signature = 'nsq:sub-first-unified-order';

    protected $description = 'NSQ订阅 - 首批订货事件';

    public function handle()
    {
        (new NsqSubscriber(config('nsq.default.address')))
            ->sub(NsqEnum::TOPIC_KFOS_FIRST_UNIFIED_ORDER, NsqEnum::CHANNEL_TIGER_FIRST_UNIFIED_ORDER,
                function (Message $message) {

                    // debug
                    if (isTest()) {
                        dump($message->data());
                    }

                    $data = $message->data();

                    Log::info("NsqSubFirstUnifiedOrderCommand in:", $data);

                    // 参数校验
                    if (!$this->valid($data)) {
                        $message->done();
                        return;
                    }

                    $this->doHandle($message->data());

                    $message->done();
                });
    }

    private function valid(array $data): bool
    {
        $validator = Validator::make($data, [
            'new_order_id' => 'required|integer',
            'shop_id'      => 'required|integer',
            'create_time'  => 'required|integer',
        ]);

        if ($validator->fails()) {
            Log::warning("NsqSubFirstUnifiedOrderCommand valid error:" . $validator->errors()->first(), $data);
            return false;
        }

        return true;
    }

    private function doHandle(array $data)
    {
        $newOrderId = $data['new_order_id'];
        $shopId     = $data['shop_id'];
        $createTime = $data['create_time'];

        $main = OpenShopMainProcessModel::getMainOrder($shopId);
        if (!$main) {
            return;
        }

        $startFeeTime = (int)date('Ymd', $createTime);

//        if ($main->startFeeTime != 0 && $main->startFeeTime != $startFeeTime) {
//
//            $shopCode = (int)OpenShopSignOrderModel::query()->where('orderNo', $main->orderNo)->value('shopCode');
//
//            BuildFs::newRobot(SendFs::ROBOT_OPEN_SHOP)
//                   ->setTitleContent('门店首批订货推送，更新年管理费', "shopId:{$shopId} shopCode:{$shopCode} 已存在年管理费收取日：{$main->startFeeTime}，现变更为：{$startFeeTime}")
//                   ->send();
//        }

        // 有年费就不更新了
        if ($main->startFeeTime != 0) {
            return;
        }

        // 更新年费
        OpenShopMainProcessModel::updateFee($main->orderNo, $startFeeTime, 0);
    }
}
